var express = require('express');
var router = express.Router();
const mysql = require('../db/mysql');


/* GET users listing. */
router.get('/', function (req, res, next) {
  res.send('respond with a resource');
});
// 获取用户列表
router.get('/usersInfo/userList', async (req, res, next) => {
  try {
    // 从请求头获取前端传递过来的参数
    let { page = 1, page_size = 10 } = req.query;
    // 第二个参数10代表十进制数
    page = parseInt(page, 10);
    page_size = parseInt(page_size, 10);
    let sql = 'select * FROM userinfo WHERE 1=1';
    let params = [];
    // 添加分页逻辑
    sql += ' LIMIT ? OFFSET ?'
    params.push(page_size, (page - 1) * page_size)
    //获取分页数据
    const users = await mysql.query(sql, params);
    // 计算总数
    const totalSql = "SELECT COUNT(*) AS total FROM userinfo WHERE 1=1"
    const totalParams = [];
    const totalResult = await mysql.query(totalSql, totalParams);
    const total = totalResult[0].total;
    // 返回数据
    res.json({
      code: 200,
      data: users,
      page_size: page_size,
      page: page,
      total: total
    })
  } catch (err) {
    console.log(err);
    res.json({
      code: 500,
      data: '服务器出错'
    })
  }
})
// 新增用户
router.post('/usersInfo/addUser', async (req, res, next) => {
  try {
    // 获取前端传递过来的参数
    const { name, password, email, phone, sex, address, role, status, remark, dept } = req.body;
    // 插入数据库

    if (name === undefined || password === undefined || status === undefined) {
      console.log('参数错误');

      return res.json({
        code: 400,
        data: '参数错误'
      });
    }
    let sql = 'INSERT INTO userinfo (name,password,email,phone,sex,address,role,status,remark,dept,createTime,updateTime) VALUES (?,?,?,?,?,?,?,?,?,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)';
    const params = [name, password, email, phone, sex, address, role, status, remark, dept];
    await mysql.query(sql, params);
    res.json({
      code: 200,
      data: '新增成功'
    })
  } catch (err) {
    console.error('Error adding user:', err); // 记录错误日志
    res.json({
      code: 200,
      data: false
    })

  }
})
// 删除用户
router.delete('/usersInfo/deleteUser', async (req, res, next) => {
  try {
    // 获取前端传递过来的参数
    const { id } = req.body;
    // 删除数据库
    if (id === undefined) {
      return res.json({
        code: 400,
        data: '参数错误'
      });
    }
    let sql = 'DELETE FROM userinfo WHERE id = ?';
    const params = [id];
    await mysql.query(sql, params);
    res.json({
      code: 200,
      data: '删除成功'
    })
  } catch (err) {
    return res.json({
      code: 500,
      data: '服务器出错'
    })
  }

})
// 编辑用户
router.put('/usersInfo/editUser', async (req, res, next) => {
  try {
    // 获取前端传递过来的参数
    const { id, name, password, email, phone, sex, address, role, status, remark, dept } = req.body;
    // 插入数据库
    let sql = 'UPDATE userinfo SET name=?,password=?,email=?,phone=?,sex=?,address=?,role=?,status=?,remark=?,dept=?,updateTime=CURRENT_TIMESTAMP WHERE id=?';
    const params = [name, password, email, phone, sex, address, role, status, remark, dept, id];
    await mysql.query(sql, params);
    res.json({
      code: 200,
      data: '编辑成功'
    })

    if (id === undefined || name === undefined || password === undefined || status === undefined) {
      return res.json({
        code: 400,
        data: '参数错误'
      });
    }
  } catch (err) {
    return res.json({
      code: 500,
      data: '服务器出错'
    })
  }

})


module.exports = router;
